package jwj8508.mvc.actions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jwj8508.mvc.dao.BoardDAO;

public class ListBoardAction implements ActionHandler {

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		// 페이징 관련 변수 선언
		int cpage = 1, perpage = 20, startno = 0;
		
		// 총페이지수, 네비게이션 시작번호, 글번호 변수
		int allpage, startnav = 1, startbno;
		
		String ftype = "", fkey = "";
		
		// 검색유형과 검색값 처리
		if (req.getParameter("findtype")!=null) {
			ftype = req.getParameter("findtype");
		}
		if (req.getParameter("findkey")!=null) {
			fkey = req.getParameter("findkey");
		}
		
		
		// cpage, startno 계산
		if (req.getParameter("cpage")!=null) {
			cpage = Integer.parseInt(req.getParameter("cpage"));
			startno = (cpage-1)*perpage;
		}
		
		// 총페이지수 계산
		int total = BoardDAO.totalBoard(ftype, fkey);
		allpage = (int)Math.ceil((total / (float)perpage));
		
		// 네비게이션 시작번호 계산
		startnav = ((cpage-1)/10)*10 + 1;
		
		// 글번호 계산
		startbno = total-(perpage*(cpage-1));
		
		String viewPage = "f|/WEB-INF/jsp/tiles/mvc.jsp";
		req.setAttribute("action", "../board/list.jsp");

		// 게시판 관련 데이터
		req.setAttribute("cpage", cpage);
		req.setAttribute("ftype", ftype);
		req.setAttribute("fkey", fkey);
		req.setAttribute("perpage", perpage);
		req.setAttribute("startno", startno);
		
		req.setAttribute("total", total);
		req.setAttribute("allpage", allpage);		
		req.setAttribute("startnav", startnav);		
		req.setAttribute("startbno", startbno);
		req.setAttribute("listBoards", BoardDAO.listBoard(startno, ftype, fkey));
		
		return viewPage;
	}

}
